
package com.insigma.business.qrcode.soldier._provider.impl;

import com.google.common.collect.Lists;

import com.insigma.business.qrcode.common.template.BasePagingResponse;
import com.insigma.business.qrcode.common.util.AdminAreaCodeUtils;
import com.insigma.business.qrcode.common.util.BizCheckUtil;
import com.insigma.business.qrcode.common.util.RedisUtils;
import com.insigma.business.qrcode.common.util.ResponseUtils;
import com.insigma.business.qrcode.common.vo.BaseDeleteRequest;
import com.insigma.business.qrcode.common.vo.BaseResponse;
import com.insigma.business.qrcode.soldier._provider.SoldierMessageInfoProvider;
import com.insigma.business.qrcode.soldier.dto.*;
import com.insigma.business.qrcode.soldier.dto.SoldierMessageInfoUpdateRequest;
import com.insigma.business.qrcode.soldier.dto.gov.BaseProviderImpl;
import com.insigma.business.qrcode.common.template.area.ServiceCallback;
import com.insigma.business.qrcode.common.template.area.ScenarioCodeEnum;
import com.insigma.business.qrcode.soldier.entity.*;
import com.insigma.business.qrcode.soldier.request.*;
import com.insigma.business.qrcode.soldier.service.*;
import com.insigma.business.qrcode.common.converter.CommonSignInfoProviderConverter;
import com.insigma.business.qrcode.common.converter.SoldierMessageInfoProviderConverter;
import com.insigma.business.qrcode.soldier.util.MiniCacheUtils;
import com.insigma.business.qrcode.soldier.util.PrivacyEncUtils;
import com.insigma.business.qrcode.soldier.util.RequestSetUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;


@Slf4j
@Service
@Component("soldierMessageInfoProvider")
public class SoldierMessageInfoProviderImpl extends BaseProviderImpl implements SoldierMessageInfoProvider {

    @Autowired
    private SoldierMessageInfoService soldierMessageInfoService;

    @Autowired
    private SoldierBasicInfoService soldierBasicInfoService;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private MiniCacheUtils miniCacheUtils;

    @Autowired
    private PlacementSoldierInfoService placementSoldierInfoService;

    @Autowired
    private CommonSignInfoService commonSignInfoService;

    @Autowired
    private SoldierOuterBasicInfoService soldierOuterBasicInfoService;

    @Override
    public BasePagingResponse<List<SoldierMessageInfoDTO>> searchSoldierMessageInfo(final SoldierMessageInfoSearchRequest searchRequest) {

        final BasePagingResponse<List<SoldierMessageInfoDTO>> basePagingResponse = new BasePagingResponse<>();
        serviceTemplate.execute(basePagingResponse, new ServiceCallback() {
            @Override
            public void check() {
                BizCheckUtil.checkNotNull(searchRequest, "查询分页SoldierMessageInfo的请求参数不能为空");
            }

            @Override
            public void executeService() {
                final SoldierMessageInfoBSearcher soldierMessageInfoBSearcher = SoldierMessageInfoProviderConverter.convertRequestSO2Searcher(searchRequest);
                final List<SoldierMessageInfoDO> soldierMessageInfoDOList = soldierMessageInfoService.search(soldierMessageInfoBSearcher);
                final List<SoldierMessageInfoDTO> soldierMessageInfoDTOList = SoldierMessageInfoProviderConverter.convertResponseDOList2DTOList(soldierMessageInfoDOList);
                ResponseUtils.buildSuccessPagingResponse(basePagingResponse, soldierMessageInfoDTOList, searchRequest,soldierMessageInfoBSearcher.getTotalCount());
            }

            @Override
            public ScenarioCodeEnum getScenarioEnum() {
                return ScenarioCodeEnum.SOLDIER_MESSAGE_INFO_SEARCH;
            }
        });

        return basePagingResponse;
    }

    @Override
    public BasePagingResponse<List<SoldierMessageInfoDTO>> searchMyMessage(SoldierMessageInfoSearchRequest searchRequest) {

        BizCheckUtil.checkNotNull(searchRequest, "请求不能为空");
        BizCheckUtil.checkNotNull(searchRequest.getSoldierId(), "soldierId不能为空");

        SoldierBasicInfoDO basicInfoDO = soldierBasicInfoService.getBySoldierId(searchRequest.getSoldierId());
        if (basicInfoDO == null) {
            return ResponseUtils.buildSuccessPagingResponse(new ArrayList<>());
        }

        final SoldierMessageInfoBSearcher soldierMessageInfoBSearcher = SoldierMessageInfoProviderConverter.convertRequestSO2Searcher(searchRequest);
        soldierMessageInfoBSearcher.setIdCardNo(basicInfoDO.getIdCardNo());
        soldierMessageInfoBSearcher.setCrowds(miniCacheUtils.getCachedSoliderCrowds(searchRequest.getSoldierId()));
        soldierMessageInfoBSearcher.setSoldierId(null);
        final List<SoldierMessageInfoDO> soldierMessageInfoDOList = soldierMessageInfoService.searchMyMessage(soldierMessageInfoBSearcher);
        final List<SoldierMessageInfoDTO> soldierMessageInfoDTOList = SoldierMessageInfoProviderConverter.convertResponseDOList2DTOList(soldierMessageInfoDOList);
        if (!CollectionUtils.isEmpty(soldierMessageInfoDTOList)) {
            // 判断是否推送过
            // 创建迭代器
            Iterator<SoldierMessageInfoDTO> iterator = soldierMessageInfoDTOList.iterator();
            while (iterator.hasNext()) {
                SoldierMessageInfoDTO soldierMessageInfoDTO = iterator.next();
                if (soldierMessageInfoDTO.getTitle().equals("公共交通优待服务推送")){
                    // 在此处添加您的条件检查
                    String idCardNo = PrivacyEncUtils.encodeIdCardNo(basicInfoDO.getIdCardNo()); // 未加密的身份证号和加密的身份证号
                    List<SoldierMessageInfoDO> temp = soldierMessageInfoService.searchBusPushed(basicInfoDO.getIdCardNo(), idCardNo);
                    if (temp.isEmpty()) {
                        // 满足条件时，删除当前数据
                        iterator.remove();
                    }
                }
            }
            for (SoldierMessageInfoDTO soldierMessageInfoDTO : soldierMessageInfoDTOList) {
                if (Strings.isNotBlank(soldierMessageInfoDTO.getCrowd())) {
                    boolean b = checkIsRead(soldierMessageInfoDTO.getId(), searchRequest.getSoldierId());
                    soldierMessageInfoDTO.setRead(b);
                }
                soldierMessageInfoDTO.setIcon(ModelIconEnum.getIcon(soldierMessageInfoDTO.getBizType()));
            }
        }

        return ResponseUtils.buildSuccessPagingResponse(soldierMessageInfoDTOList, soldierMessageInfoBSearcher);
    }

    @Override
    public BaseResponse<List<SoldierMessageInfoDTO>> listRemindAndUnreadMessageInfo(String soldierId) {

        BizCheckUtil.checkNotBlank(soldierId, "id不能为空");

        SoldierBasicInfoDO bySoldierId = soldierBasicInfoService.getBySoldierId(soldierId);
        if (bySoldierId == null) {
            SoldierOuterBasicInfoDO outerBasicInfoDO = soldierOuterBasicInfoService.getBySoldierId(soldierId);
            if (outerBasicInfoDO == null) {
                return ResponseUtils.buildSuccessResponse(new ArrayList<>());
            }
            bySoldierId = new SoldierBasicInfoDO();
            bySoldierId.setIdCardNo(outerBasicInfoDO.getIdCardNo());
            bySoldierId.setRealName(outerBasicInfoDO.getRealName());
            bySoldierId.setSoldierId(outerBasicInfoDO.getSoldierId());
        }

        List<SoldierMessageInfoDO> result = Lists.newArrayList();

        List<SoldierMessageInfoDO> soldierMessageInfoDOS = soldierMessageInfoService.listRemindAndUnreadMessageInfoByIdCardNo(bySoldierId.getIdCardNo());
        result.addAll(soldierMessageInfoDOS);

        List<SoldierMessageInfoDO> allCrowdAndValid =  soldierMessageInfoService.listAllCrowdAndValid();
        if (!CollectionUtils.isEmpty(allCrowdAndValid)) {
            for (SoldierMessageInfoDO soldierMessageInfoDO : allCrowdAndValid) {
                if (!checkIsRead(soldierMessageInfoDO.getId(), soldierId)) {
                    result.add(soldierMessageInfoDO);
                }
            }
        }

        final List<SoldierMessageInfoDTO> soldierMessageInfoDTOList = SoldierMessageInfoProviderConverter.convertResponseDOList2DTOList(result);
        return ResponseUtils.buildSuccessResponse(soldierMessageInfoDTOList);
    }

    @Override
    public BaseResponse<List<SoldierMessageInfoDTO>> listNotSignMessageOfPlacement(String soldierId) {

        BizCheckUtil.checkNotBlank(soldierId, "id不能为空");
        PlacementSoldierInfoDO bySoldierId = placementSoldierInfoService.getBySoldierId(soldierId);
        BizCheckUtil.checkNotNull(bySoldierId, "查无此人");
        List<SoldierMessageInfoDO> soldierMessageInfoDOS = soldierMessageInfoService.listByBizType(MessageTypeEnum.PLACEMENT.name());

        List<SoldierMessageInfoDTO> list = Lists.newArrayList();
        if (!CollectionUtils.isEmpty(soldierMessageInfoDOS)) {
            for (SoldierMessageInfoDO soldierMessageInfoDO : soldierMessageInfoDOS) {
                CommonSignInfoDO message = commonSignInfoService.getBy("MESSAGE", soldierMessageInfoDO.getId(), bySoldierId.getIdCardNo());
                if (message == null) {
                    list.add(SoldierMessageInfoProviderConverter.convertResponseDO2DTO(soldierMessageInfoDO));
                }
            }
        }
        return ResponseUtils.buildSuccessResponse(list);
    }

    @Override
    public BaseResponse<String> addMessageOfPlacement(SoldierMessageInfoInsertRequest request) {

        BizCheckUtil.checkNotNull(request, "请求不能为空");
        BizCheckUtil.checkNotBlank(request.getDetail(), "详情不能为空");
        SoldierMessageInfoDO messageInfoDO = new SoldierMessageInfoDO();
        messageInfoDO.setBizType(MessageTypeEnum.PLACEMENT.name());
        messageInfoDO.setCrowd("AZ");
        messageInfoDO.setMaterialType(MessageMaterialTypeEnum.RTF.name());
        messageInfoDO.setTitle("安置信息");
        messageInfoDO.setIntroduction("安置信息");
        messageInfoDO.setDetail(request.getDetail());
        messageInfoDO.setValidPeriod(false);
        messageInfoDO.setRead(false);
        messageInfoDO.setRemind(false);
        messageInfoDO.setPublished(true);
        soldierMessageInfoService.insert(messageInfoDO);
        return ResponseUtils.buildSuccessResponse(messageInfoDO.getId());
    }

    @Transactional
    @Override
    public BaseResponse<String> batchAddMessageOfPlacement(SoldierMessageInfoInsertRequest request) {

        BizCheckUtil.checkNotNull(request, "请求不能为空");
        BizCheckUtil.checkNotBlank(request.getDetail(), "详情不能为空");
        BizCheckUtil.checkIsTrue(!CollectionUtils.isEmpty(request.getIdCardNoList()), "身份证列表不能为空");

        final SoldierMessageInfoDO soldierMessageInfoDO = SoldierMessageInfoProviderConverter.convertRequestIO2DO(request);
        for (String idCardNo : request.getIdCardNoList()) {
            SoldierBasicInfoDO byIdCardNo = soldierBasicInfoService.getByIdCardNo(idCardNo);
            if (byIdCardNo != null) {
                soldierMessageInfoDO.setRealName(byIdCardNo.getRealName());
                soldierMessageInfoDO.setIdCardNo(byIdCardNo.getIdCardNo());
                soldierMessageInfoDO.setSoldierId(byIdCardNo.getSoldierId());
                soldierMessageInfoService.insert(soldierMessageInfoDO);
            }
        }

        return ResponseUtils.buildSuccessResponse(String.valueOf(request.getIdCardNoList().size()));
    }

    @Override
    public BaseResponse<String> addMessageSignOfPlacement(CommonSignInfoInsertRequest request) {

        BizCheckUtil.checkNotNull(request, "请求不能为空");
        BizCheckUtil.checkNotBlank(request.getSoldierId(), "soldierId不能为空");

        PlacementSoldierInfoDO bySoldierId = placementSoldierInfoService.getBySoldierId(request.getSoldierId());
        BizCheckUtil.checkNotNull(bySoldierId, "查无此人");
        final CommonSignInfoDO commonSignInfoDO = CommonSignInfoProviderConverter.convertRequestIO2DO(request);
        commonSignInfoDO.setType("MESSAGE");
        commonSignInfoDO.setIdCardNo(bySoldierId.getIdCardNo());
        commonSignInfoService.insert(commonSignInfoDO);
        return ResponseUtils.buildSuccessResponse(commonSignInfoDO.getId());
    }

    @Override
    public BaseResponse<SoldierMessageStatusDTO> countNotReadMessage(String soldierId) {

        BizCheckUtil.checkNotNull(soldierId, "id不为空");
        String cachedIdCardNo = miniCacheUtils.getCachedIdCardNo(soldierId);
        if (Strings.isBlank(cachedIdCardNo)) {
            return ResponseUtils.buildSuccessResponse(new SoldierMessageStatusDTO());
        }

        int i = soldierMessageInfoService.countUnreadOfIdCardNo(cachedIdCardNo);

        SoldierMessageInfoBSearcher soldierMessageInfoBSearcher = new SoldierMessageInfoBSearcher(1, Integer.MAX_VALUE);
        soldierMessageInfoBSearcher.setCrowds(miniCacheUtils.getCachedSoliderCrowds(soldierId));
        soldierMessageInfoBSearcher.setValid(true);
        final List<SoldierMessageInfoDO> soldierMessageInfoDOList = soldierMessageInfoService.searchMessageOfCrowd(soldierMessageInfoBSearcher);
        final List<SoldierMessageInfoDTO> soldierMessageInfoDTOList = SoldierMessageInfoProviderConverter.convertResponseDOList2DTOList(soldierMessageInfoDOList);
        if (!CollectionUtils.isEmpty(soldierMessageInfoDTOList)) {
            for (SoldierMessageInfoDTO soldierMessageInfoDTO : soldierMessageInfoDTOList) {

                boolean validFlag = checkIsValidPeriod(soldierMessageInfoDTO);
                if (validFlag) {
                    boolean b = checkIsRead(soldierMessageInfoDTO.getId(), soldierId);
                    if (!b) {
                        i++;
                    }
                }
            }
        }

        return ResponseUtils.buildSuccessResponse(new SoldierMessageStatusDTO(i));
    }

    private boolean checkIsValidPeriod(SoldierMessageInfoDTO soldierMessageInfoDTO) {
        if (Boolean.TRUE.equals(soldierMessageInfoDTO.getValidPeriod())) {
            Date date = new Date();
            if (date.compareTo(soldierMessageInfoDTO.getEndDatetime()) > 0) {
                return false;
            }
            if (date.compareTo(soldierMessageInfoDTO.getBeginDatetime()) < 0) {
                return false;
            }
        }
        return true;
    }


    private boolean checkIsRead(String id, String soldierId) {
        String key = "ALL_CROWD_MESSAGE_" + id;
        boolean b = redisUtils.sHasKey(key, soldierId);
        return b;
    }

    private void setAllCrowdMessageAsRead(String id, String soldierId) {
        String key = "ALL_CROWD_MESSAGE_" + id;
        redisUtils.sSet(key, soldierId);
    }

    @Override
    public BaseResponse<Integer> setMessageRead(String id, String soldierId) {

        BizCheckUtil.checkNotBlank(id, "id不能为空");

        int i=0;
        SoldierMessageInfoDO soldierMessageInfoDO = soldierMessageInfoService.get(id);
        BizCheckUtil.checkNotNull(soldierMessageInfoDO, "消息不存在");
        if (Strings.isNotBlank(soldierMessageInfoDO.getCrowd())) {
            setAllCrowdMessageAsRead(id, soldierId);
        } else {
            soldierMessageInfoDO.setRead(true);
            i = soldierMessageInfoService.update(soldierMessageInfoDO);
        }

        return ResponseUtils.buildSuccessResponse(i);
    }



    @Override
    public BaseResponse<SoldierMessageInfoDTO> getSoldierMessageInfo(final BaseGetRequest baseGetRequest){

        final BaseResponse<SoldierMessageInfoDTO> baseResponse = new BaseResponse<>();
        serviceTemplate.execute(baseResponse, new ServiceCallback() {
            @Override
            public void check() {
                BizCheckUtil.checkNotNull(baseGetRequest, "获取单条SoldierMessageInfo的请求参数不能为空");
                BizCheckUtil.checkNotBlank((String)baseGetRequest.getId(), "id不能为空");
            }

            @Override
            public void executeService() {
                final SoldierMessageInfoDO soldierMessageInfoDO = soldierMessageInfoService.get((String)baseGetRequest.getId());
                final SoldierMessageInfoDTO remoteObj = SoldierMessageInfoProviderConverter.convertResponseDO2DTO(soldierMessageInfoDO);
                if (remoteObj != null) {
                    MessageTypeEnum byEnumName = MessageTypeEnum.getByEnumName(remoteObj.getBizType());
                    if (byEnumName != null) {
                        remoteObj.setBizTypeName(byEnumName.getDesc());
                    }
                }
                ResponseUtils.setupSuccessResponse(baseResponse,remoteObj);
            }
            @Override
            public ScenarioCodeEnum getScenarioEnum() {
                return ScenarioCodeEnum.SOLDIER_MESSAGE_INFO_GET;
            }
        });
        return baseResponse;
    }


    @Override
    public BaseResponse<String> insertSoldierMessageInfo(final SoldierMessageInfoInsertRequest insertRequest){

        final BaseResponse<String> baseResponse = new BaseResponse<>();
        serviceTemplate.execute(transactionTemplate, baseResponse, new ServiceCallback() {
            @Override
            public void check() {
                BizCheckUtil.checkNotNull(insertRequest, "新增SoldierMessageInfo的请求参数不能为空");
            }
            @Override
            public void executeService() {
                final SoldierMessageInfoDO soldierMessageInfoDO = SoldierMessageInfoProviderConverter.convertRequestIO2DO(insertRequest);
                soldierMessageInfoService.insert(soldierMessageInfoDO);
                ResponseUtils.setupSuccessResponse(baseResponse, soldierMessageInfoDO.getId());
            }

            @Override
            public ScenarioCodeEnum getScenarioEnum() {
                return ScenarioCodeEnum.SOLDIER_MESSAGE_INFO_INSERT;
            }
        });
        return baseResponse;
    }


    @Override
    public BaseResponse<Integer> updateSoldierMessageInfo(final SoldierMessageInfoUpdateRequest updateRequest){

        final BaseResponse<Integer> baseResponse = new BaseResponse<>();
        serviceTemplate.execute(transactionTemplate, baseResponse, new ServiceCallback() {
            @Override
            public void check() {
                BizCheckUtil.checkNotNull(updateRequest, "修改SoldierMessageInfo的请求参数不能为空");
                BizCheckUtil.checkNotBlank(updateRequest.getId(), "id不能为空");
            }
            @Override
            public void executeService() {
                SoldierMessageInfoDO soldierMessageInfoDO = SoldierMessageInfoProviderConverter.convertRequestUO2DO(updateRequest);
                Integer affectRowNum = soldierMessageInfoService.update(soldierMessageInfoDO);
                ResponseUtils.setupSuccessResponse(baseResponse, affectRowNum);
            }
            @Override
            public ScenarioCodeEnum getScenarioEnum() {
                return ScenarioCodeEnum.SOLDIER_MESSAGE_INFO_UPDATE;
            }
        });
        return baseResponse;
    }

    @Override
    public BaseResponse<Integer> publishMessage(SoldierMessageInfoUpdateRequest request) {

        BizCheckUtil.checkNotNull(request, "修改SoldierMessageInfo的请求参数不能为空");
        BizCheckUtil.checkNotBlank(request.getId(), "id不能为空");
        BizCheckUtil.checkNotNull(request.getPublished(), "published不能为空");
        SoldierMessageInfoDO messageInfoDO = soldierMessageInfoService.get(request.getId());
        BizCheckUtil.checkNotNull(messageInfoDO, "消息不存在");
        messageInfoDO.setPublished(request.getPublished());
        RequestSetUtils.setModifierInfo(messageInfoDO, request);
        soldierMessageInfoService.update(messageInfoDO);

        return ResponseUtils.buildSuccessResponse(0);
    }


    @Override
    public BaseResponse<Integer> deleteSoldierMessageInfo(final BaseDeleteRequest deleteRequest){

        final BaseResponse<Integer> baseResponse = new BaseResponse<>();
        serviceTemplate.execute(transactionTemplate, baseResponse, new ServiceCallback() {
            @Override
            public void check() {
                BizCheckUtil.checkNotNull(deleteRequest, "逻辑删除SoldierMessageInfo的请求参数不能为空");
                BizCheckUtil.checkNotBlank((String)deleteRequest.getId(), "id不能为空");
                BizCheckUtil.checkNotBlank(deleteRequest.getModifierType(),"操作人类型不能为空");
                BizCheckUtil.checkNotBlank((String)deleteRequest.getModifierId(),"操作人不能为空");
            }
            @Override
            public void executeService() {
                final Integer affectRowNum = soldierMessageInfoService.delete((String)deleteRequest.getId(),deleteRequest.getModifierType(),(String)deleteRequest.getModifierId());
                ResponseUtils.setupSuccessResponse(baseResponse, affectRowNum);
            }
            @Override
            public ScenarioCodeEnum getScenarioEnum() {
                return ScenarioCodeEnum.SOLDIER_MESSAGE_INFO_DELETE_LOGICALLY;
            }
        });
        return baseResponse;
    }

    @Override
    public BasePagingResponse<List<SoldierJobMessageInfoDTO>> searchJobMessageStats(CommonLedgerStatsRequest request) {

        boolean b = request.convertTime();
        if (!b) {
            return ResponseUtils.buildSuccessPagingResponse(null);
        }

        SoldierMessageInfoBSearcher searcher = new SoldierMessageInfoBSearcher(request.getPageNo(), request.getPageSize());
        searcher.setBizType("UNEMPLOYMENT");
        searcher.setAdminAreaCode(AdminAreaCodeUtils.getCutdAreaCode(request.getAdminAreaCode()));
        searcher.setStartTime(request.getStartTime());
        searcher.setEndTime(request.getEndTime());
        searcher.setSortKeyValueJoint("createDatetime_desc");
        final List<SoldierMessageInfoDO> soldierMessageInfoDOList = soldierMessageInfoService.search(searcher);

        final List<SoldierMessageInfoDTO> soldierMessageInfoDTOList = SoldierMessageInfoProviderConverter.convertResponseDOList2DTOList(soldierMessageInfoDOList);

        List<SoldierJobMessageInfoDTO> result = Lists.newArrayList();
        for (SoldierMessageInfoDTO soldierMessageInfoDTO : soldierMessageInfoDTOList) {
            SoldierJobMessageInfoDTO item = new SoldierJobMessageInfoDTO();
            BeanUtils.copyProperties(soldierMessageInfoDTO, item);

            item.setContent(soldierMessageInfoDTO.getIntroduction());
            String[] split = soldierMessageInfoDTO.getIntroduction().split(",");
            if (split.length > 1) {
                String replace = split[0].replace("推荐公司:", "");
                item.setCompanyName(replace);
            }
            item.setPositionName(soldierMessageInfoDTO.getTitle().replace("推荐职位:", ""));
            result.add(item);
        }
        return ResponseUtils.buildSuccessPagingResponse(result, searcher);
    }
}
